<?php

/*
    Open Designs Content Management System (odCMS)
    Copyright (C) 2010  Thomas Wong - tom@ztml.org

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
*/

class io extends init

{	
	/*------------------\
        | connect to sqlite |
        \------------------*/
	function sqlite()
	{
		if(file_exists("./odcms.tpls"))
		{
			$this->TEMPLATES = new SQLiteDatabase("./odcms.tpls");

		}
		elseif( !file_exists("../templates/odcms.tpls") )
		{
			echo $this->_CC_['USITE']. " - ($this->cwd) <font size='6' color='orange'> FATAL: Database error!</font>".
					" <br /><br />Can't open templates database file.";
			$_SESSION['usite'] = "";
			exit;
		}
		else
		{
			$this->TEMPLATES = new SQLiteDatabase("../templates/odcms.tpls"); // templates database
		}

		if( !file_exists("./members.dbf") )
		{
			$this->MEMBERS = new SQLiteDatabase("./members.dbf"); // members database
			$this->createDbase("member","members");
		}
		else
		{
			$this->MEMBERS = new SQLiteDatabase("./members.dbf"); // members database
		}

		if(!file_exists("./users/$this->username/contents.dbf"))
		{
			$this->_CC_['member'] = $this->username = "admin";
		}
		$this->UDB   = new SQLiteDatabase("./users/$this->username/contents.dbf"); // user content database
		$this->BLOG  = new SQLiteDatabase("./users/$this->username/blog.dbf"); // user blog database

		$this->localDbase();
	}
	
	/*--------------------\
        | reset user password |
        \--------------------*/
	function resetPassword($uname)
	{
		$q = new SQLiteDatabase("./users/$uname/contents.dbf"); // user content database
		$password = crypt($uname,$uname);
		if($q)
		{
			$q->query("UPDATE _profile_ SET Password='$password' WHERE uName='$uname'");
			echo "Password is reset for $uname";
		}
		else
		{
			echo "$uname not found!";
		}
		exit;
	}
	
	/*------------------------\
        | get username form email |
        \------------------------*/
	function getUserName($email)
	{
		$q = $this->MEMBERS->query("SELECT ID FROM members WHERE eMail='$email'");
		list($uname) = $q->fetch();
		return $uname;
	}		
	
        /*-----------------\
        | get user profile |
        \-----------------*/
	function getProfile()
	{
		$site = $this->_CC_['WEBSITE'];
		$this->_CC_['my_credits'] = "";
		$date = $this->_CC_['datetime'];
		$q = $this->UDB->query("SELECT * FROM _profile_ WHERE uName='$this->username'");
		if(!$q)
		{
			$password = crypt($this->username,$this->username);
			$this->addProfile($this->username,"00000","00","First","Last","$password","$this->username@$site",
					  "Anytown","US","About $this->username","$this->username","$this->username","$this->username",
					  "&copy; $this->username","smarkup.edt","PopUp","default",$date,$date);
			
			$q = $this->UDB->query("SELECT * FROM _profile_ WHERE uName='$this->username'");
		}
		else
		{
			list ( $this->_CC_['uname'],$this->_CC_['zip'],$this->_CC_['district'],$this->_CC_['state'],$this->_CC_['city'],
			       $this->_CC_['fname'],$this->_CC_['lname'],$about,$this->_CC_['password'],
			       $this->_CC_['email'],$this->_CC_['cname'],$this->_CC_['ctitle'],$this->_CC_['slogan'],
			       $this->_CC_['copyright'],$this->_CC_['editor'],$this->_CC_['emode'],$this->_CC_['template'],
			       $this->_CC_['cdate'],$this->_CC_['mdate']
			     ) 
					= $q->fetch();
			
			list($this->_CC_['zip5'],$this->_CC_['zip4'])  = explode("-",$this->_CC_['zip']);
			list($this->_CC_['about'],$this->_CC_['meta']) = explode("^^^^^",stripslashes($about));
			
			$this->_CC_['META'] .= $this->_CC_['meta'];
		}
		$this->_CC_['site'] = $this->_CC_['company'] = $this->_CC_['cname'];
		if(!$this->_CC_['site']) $this->_CC_['site'] = $this->username;
		
		$q = $this->MEMBERS->query("SELECT Name,Website,Points,pSpent,Credits,cUsed,cPaid,cLimit FROM members WHERE ID='$this->username'");
		list($name,$website,$this->_CC_['points'],$this->_CC_['spent'],$credits,$cused,$cpaid,$climit) = $q->fetch();
		if(!$website)
		{
			$this->_CC_['upgrade'] = "<a href='?Page=_upgrade_'>Upgrade Account ($this->username)</a>";
		}
		else
		{
			$this->_CC_['Website'] = "<a href='http://$website/?usite=$this->username' title='Go to my website'>My Website</a>";
		}
		if($_SESSION['UserName']==$this->username)
		{
			$this->_CC_['my_credits'] = "<tr><th class='profile' valign='top'>Credits:</th>".
				"<td class='profile'>Balance: $credits &nbsp;&nbsp;&nbsp; Used: $cused &nbsp;&nbsp;&nbsp; Paid: $cpaid &nbsp;&nbsp;&nbsp; Limit: $climit</td></tr>";
		}

		return;
	}

        /*-----------------\
        | add user profile |
        \-----------------*/
	function addProfile($uname,$zip,$dist,$fname,$lname,$password,$email,$city,$state,$about,$sname,$stitle,$slogan,
			    $copyr,$editor,$mode,$theme,$cdate,$mdate)
	{
		$fname  = sqlite_escape_string($fname);
		$lname  = sqlite_escape_string($lname);
		$about  = sqlite_escape_string($about);
		$city   = sqlite_escape_string($city);
		$slogan	= sqlite_escape_string($slogan);
			
		$this->createDbase("profile","_profile_");
		$this->UDB->query("INSERT INTO _profile_ VALUES('$uname','$zip','$dist','$state','$city','$fname','$lname',".
				      "'$about','$password','$email','$sname','$stitle','$slogan',".
				      "'$copyr','$editor','$mode','$theme','$cdate','$mdate')");
		return;
	}
		
        /*--------------------\
        | get login user name |
        \--------------------*/
	function getLoginUser($name)
	{
		$q = $this->MEMBERS->query("SELECT Name FROM members WHERE ID='$name'");
		list($this->_CC_['luser']) = $q->fetch();
	}
	
        /*----------------\
        | get editor file |
        \----------------*/
	function getEditor($file_name)
	{
		list($fname,$ext) = explode(".",$file_name);
		if(!$ext) $ext = "edt";
		$fname .= ".$ext";

		return @file_get_contents("../templates/editors/$fname");
	}
		
        /*----------------------\
        | delete theme template |
        \----------------------*/
	function setTheme($template)
	{
		$member = $_SESSION['UserName'];
		if(!$member || !$_SESSION['CWD']) return;
		
		$this->PROFILE = new SQLiteDatabase("../".$_SESSION['CWD']."/users/$member/contents.dbf"); // user profile database
		$this->PROFILE->query("UPDATE _profile_ SET Template='$template'");
		$this->_CC_['Page'] = "";
		if($this->_CC_['USITE']=="_members") $this->_CC_['Page'] = "Profile";
		$this->_CC_['template'] = $template;
	}
	
        /*--------------\
        | get menu file |
        \--------------*/
	function getMenuData()
	{
		if($_REQUEST['form'])
		{
			$this->_CC_['Page'] = $_REQUEST['form'].".".$this->_CC_['Main'];
		}
		/*if(!$this->_CC_['theme'])
		{
			$this->_CC_['theme'] = $this->_CC_['template'];
		}*/

		list($this->_CC_['Page'],$this->_CC_['Main']) = explode(".",$this->_CC_['Page']);
		
		$this->_CC_['Levels'] = "";
		$page = $this->_CC_['Main'];
		if(!$page) $page = $this->_CC_['Page'];
		if( $page) $this->getMenuLevels($page);
		
		$this->_CC_['Levels'] .= " &#187; ".$this->_CC_['Page'];
		$this->_CC_['mainPage'] = $this->_CC_['Main'];
		if(!$this->_CC_['mainPage']) $this->_CC_['mainPage'] = $this->_CC_['Page'];
		if(!$this->_CC_['thisLevel']) $this->_CC_['thisLevel'] = "<a href='#'>".$this->_CC_['Page']."</a>";

		$this->getMenuItems("menu1","menu1");	
		$this->getMenuItems("menu2","menu2");
		$this->getMenuItems("menu3","menu3");

		$main = $this->_CC_['Main'];
		$page = $this->_CC_['Page'];
		if(!$this->getMenuItems($page,"sub_menu"))
		{
			$this->getMenuItems($main,"sub_menu");
		}
		if(!$this->_CC_['ThisPage']) $this->getMenuItems($main,"this_menu");

		$this->_CC_['MainPage'] = preg_replace("/_/"," ",$this->_CC_['MainPage']);
	}
	
        /*--------------\
        | get menu file |
        \--------------*/
	function getMenuItems($page,$menu)
	{
		$size = $this->getMenuList($page,$menu);
		if(!$size) return 0;
                for($ix=0;$ix<$size;$ix++)
                {
			if(!$this->_CC_['Page'] && !$this->_CC_[$menu."Hide_$ix"]) $this->_CC_['Page'] = $this->_CC_[$menu."Name_$ix"];
			
			if($this->_CC_['Page']==$this->_CC_[$menu."Name_$ix"])
			{
				if(!$_REQUEST['preview'] && !$_REQUEST['theme'])
				{
					//$this->_CC_['udfTHEME'] = $this->_CC_['theme'] = $this->_CC_[$menu."Theme_$ix"];
					if($this->_CC_[$menu."Theme_$ix"]) $this->_CC_['theme'] = $this->_CC_[$menu."Theme_$ix"];
				}
				
				if($this->_CC_[$menu."Title_$ix"])
				{
					$this->_CC_['ptitle'] = $this->_CC_[$menu."Title_$ix"];
					if(!$this->_CC_['title'])
					{
						$this->_CC_['title'] = $this->_CC_['uname'].": ".$this->_CC_['ptitle']." | ".
							$this->_CC_['cname']." - ".$this->_CC_['slogan'];
					}
				}
				$this->_CC_['TYPE'] = $this->_CC_[$menu."Type_$ix"];
				if($this->_CC_['TYPE']=="redirect")
				{
					header("location: ".$this->_CC_['ptitle']);
					echo "<h3>Error encountered while redirecting...</h3><a href='".$this->_CC_['ptitle'].
							"'>Click here to continue...</a>";
					exit;
				}

				list($meta,$set) = explode("^^^",$this->_CC_[$menu."Meta_$ix"]);
				$this->_CC_['META'] .= $meta;
				if($set) $this->opUdfMsgs($set);
				$this->_CC_['pdesc'] = $this->_CC_[$menu."Desc_$ix"];
				$this->_CC_['DESC']  = $this->subString($this->_CC_['pdesc']);
				$this->_CC_['attrs'] = $this->_CC_[$menu."Attrs_$ix"];
				$this->_CC_['DATE']  = $this->_CC_[$menu."Date_$ix"];
				$this->_CC_['MID']   = $this->_CC_[$menu."MID_$ix"];
				$this->_CC_['MENU']  = $menu;
			
				$prev = $ix-1; $next = $ix+1; $last=$size-1;
				$ext  = "";
				//$this->_CC_['MainPage'] = $this->_CC_['Page'];
				if($this->_CC_[$menu."Main_$ix"])
				{
					$this->_CC_['Parent'] = $this->_CC_[$menu."Main_$ix"];
					//if($this->_CC_[$menu."Main_$ix"]!="menu1" && $this->_CC_[$menu."Main_$ix"]!="menu2" && $this->_CC_[$menu."Main_$ix"]!="menu3")
						$this->_CC_['MainPage'] = $this->_CC_[$menu."Main_$ix"];
					$ext = ".".$this->_CC_[$menu."Main_$ix"];
				}
				if(!$this->_CC_['Parent']) $this->_CC_['Parent'] = $menu;
				$this->_CC_['ThisPage'] = "Page=".$this->_CC_['Page'].$ext;

				$this->_CC_['FirstPage']= "Page=".$this->_CC_[$menu."Name_0"].$ext;
				$this->_CC_['LastPage'] = "Page=".$this->_CC_[$menu."Name_$last"].$ext;
				$this->_CC_['PrevPage'] = $this->_CC_['NextPage'] = $this->_CC_['ThisPage'];

				if($this->_CC_[$menu."Name_$prev"]) $this->_CC_['PrevPage'] = "Page=".$this->_CC_[$menu."Name_$prev"].$ext;
				if($this->_CC_[$menu."Name_$next"]) $this->_CC_['NextPage'] = "Page=".$this->_CC_[$menu."Name_$next"].$ext;
				return 1;
			}
		}
		return $ix;
	}

        /*--------------\
        | get menu list |
        \--------------*/
	function getMenuList($page,$menu)
	{
		$page = preg_replace("/ /","_",$page);
		
		if(is_numeric($page)) $page = "t_$page";
		$q = @$this->UDB->query("SELECT * FROM $page ORDER BY mid");
		if ($q === false)
		{
			return;
		}
		$ix = 0;
		while( $q->valid() )
		{
			list($this->_CC_[$menu."Name_$ix"],$this->_CC_[$menu."MID_$ix"],$main,
			     $this->_CC_[$menu."Type_$ix"],$this->_CC_[$menu."Hide_$ix"],
			     $this->_CC_[$menu."Theme_$ix"],$this->_CC_[$menu."Title_$ix"],
			     $this->_CC_[$menu."Attrs_$ix"],$this->_CC_[$menu."Meta_$ix"],
			     $this->_CC_[$menu."Desc_$ix"], $this->_CC_[$menu."Date_$ix"]) = $q->current();
			list($this->_CC_[$menu."Main_$ix"],$this->_CC_[$menu."Parent_$ix"]) = explode("^",$main);
			$q->next();
			$ix++;
		}
		$this->_CC_[$menu."Size"] = $ix;
		return $ix;
	}
	
        /*----------------\
        | get menu levels |
        \----------------*/
	function getMenuLevels($page)
	{
		$page1 = preg_replace("/ /","_",$page);
		$q = @$this->UDB->query("SELECT Main FROM $page1");
		
		if ($q === false)
		{
			$this->_CC_['Levels'] .= " &#187; <a href='?Page=$page'>$page</a>";
			$this->_CC_['thisLevel'] = "<a href='?Page=$page'>$page</a>";
			return;
		}
		list($main) = $q->fetch();
		list($page,$main) = explode("^",$main);
		$page = preg_replace("/_/"," ",$page);
		if($main == "menu1" || $main == "menu2" || $main == "menu3")
		{
			$this->_CC_['Levels'] .= " &#187; <a href='?Page=$page'>$page</a>";
			$page = preg_replace("/ /","_",$page);
			$main = $this->_CC_['Page'];
			if($_REQUEST['Page']!="$main.$page")
			{	
				$this->_CC_['thisLevel'] = "<a href='?Page=$main.$page'>$main</a>";
			}
			else
			{
				$page = preg_replace("/_/"," ",$page);
				$this->_CC_['thisLevel'] = "<a href='?Page=$page'>$page</a>";
			}
			return;
		}
		if($main) $this->getMenuLevels($main);
		$this->_CC_['Levels'] .= " &#187; <a href='?Page=$page.$main'>$page</a>";
		$this->_CC_['thisLevel'] = "<a href='?Page=$page.$main'>$page</a>";
	}
	
	/*-------------------------------\
        | get theme and editor selection |
        \-------------------------------*/
	function getSelectList($editor,$theme)
	{
		$selected = $theme;
		if(!$selected) $selected = "SELECT";
		$this->_CC_['themes']  = "<option value='$theme' selected='selected'> $selected </option>\n";
		if($this->_CC_['T_LIST'])
		{
			$this->_CC_['themes'] .= $this->_CC_['T_LIST'];
			return;
		}

		$editors = array();
		$themes  = array($theme);

		if ($editor)
		{
			if($handle = opendir("../templates/editors/"))
			{
				$this->_CC_['editors'] = "<option value='$editor' selected='selected'> $editor </option>\n";
				while (false !== ($file = readdir($handle)))
				{
					if(preg_match("/^(.*)\.edt$/",$file,$regs))
					{
						array_push($editors,$regs[1]);
					}
				}
				closedir($handle);
				sort($editors);
				foreach ($editors as $key => $val)
				{
					$this->_CC_['editors'] .= "<option value='$val'> $val </option>\n";
				}
			}
		}

		if ($editor && $handle = opendir("../templates/"))
		{
			while (false !== ($file = readdir($handle)))
			{
				if(preg_match("/^(.*)\.tpl$/",$file,$regs))
				{
					array_push($themes,$regs[1]);
				}
			}
			closedir($handle);
		}
		if ($handle = opendir("./users/$this->username/"))
		{
			while (false !== ($file = readdir($handle)))
			{
				if(preg_match("/^(.*)\.tpl$/",$file,$regs))
				{
					array_push($themes,$regs[1]);
				}
			}
			closedir($handle);
		}
		
		sort($themes);
		foreach ($themes as $key => $val)
		{
			if($val == $theme || $val=="Select") continue;
			$theme = $val;
			$this->_CC_['T_LIST'] .= "<option value='$val'> $val </option>\n";
		}
		$this->_CC_['themes'] .= $this->_CC_['T_LIST'];
	}

        /*-----------------\
        | get user content |
        \-----------------*/
	function getUserContent($page,$type)
	{
		$page  = sqlite_escape_string($page);
		$q = @$this->UDB->query("SELECT * FROM Document WHERE Name='$page'");
		if ($q === false)
		{
			$this->createDbase("document","Document");
			$this->_CC_['content'] = "Please use cPanel to create a page";
			return 1;
		}
		list($name,$this->_CC_['ID'],$this->_CC_['PgType'],$this->_CC_['header'],$this->_CC_['content'],$this->_CC_['mdate'])
				= $q->fetch();
		if(!$name)
		{
			$this->_CC_['content'] = "<h3>Page ".$this->_CC_['Page']." not found</h3><p> ".
				"Please use <a href='?Page=_sitemap_'>SiteMap</a> for available pages</p>";
			return 1;
		}
		if($type=="update") return 1;
		list($this->_CC_['content'],$this->_CC_['content_1'],$this->_CC_['content_2'],$this->_CC_['content_3'],
		     $this->_CC_['content_4'],$this->_CC_['content_5']) = explode("^^^",$this->_CC_['content']);

		$this->_CC_['content'] = $this->subString($this->_CC_['content']);

		if($this->_CC_['content_1']) $this->_CC_['content_1'] = $this->subString($this->_CC_['content_1']);
		if($this->_CC_['content_2']) $this->_CC_['content_2'] = $this->subString($this->_CC_['content_2']);
		if($this->_CC_['content_3']) $this->_CC_['content_3'] = $this->subString($this->_CC_['content_3']);
		if($this->_CC_['content_3']) $this->_CC_['content_4'] = $this->subString($this->_CC_['content_4']);
		if($this->_CC_['content_3']) $this->_CC_['content_5'] = $this->subString($this->_CC_['content_5']);

		return 0;
	}
	
        /*----------------------\
        | get document sections |
        \----------------------*/
	function getDocSections($page)
	{
		$q = @$this->UDB->query("SELECT * FROM Document WHERE Type='Attachment' ORDER BY cid");
		if ($q === false)
		{
			return;
		}
		$snum = 0;
		$this->_CC_['flag'] = 1;
		while( $q->valid() )
		{
			list($title,$cid,$type,$this->_CC_["header_$snum"],$content) = $q->current();
			$this->_CC_["section_$snum"] = $this->subString($content);
			$edit = "";
			if($this->username==$_SESSION['UserName'] && $this->cwd == $_SESSION['CWD'])
			{
				$this->_CC_['section_number'] = $cid;
				$this->_CC_['header_number']  = $this->_CC_["header_$snum"];
				if(!$_GET['generate']) $edit = $this->getUdfMsg("udf_062");
			}
			$this->_CC_["section_$snum"] = $edit.stripslashes($this->subString($content));
			$snum++;

			$q->next();
		}
	}
			
	/*---------------------\
        | get designer designs |
        \---------------------*/
	function getDesigner()
	{
		$this->getDesigns($this->_CC_['author'],1);
	}
	
	/*------------\
        | get designs |
        \------------*/
	function getDesigns($name,$flag)
	{
		if($name=="Table")
		{
			$save = $this->_CC_['content'];
			$this->_CC_['content'] = "";
			$this->dispTable("");
			$this->_CC_['t_content'] = $this->_CC_['content'];
			$this->_CC_['content']   = $save;
			return;
		}
		
		$this->_CC_['header'] = "";
		$this->_CC_['content'] = $this->getFormData("designs_style");
		$dlist = array();

		$dir = "../designs/$name";
		if ($handle = opendir("$dir/"))
		{
			while (false !== ($file = @readdir($handle)))
			{
				if(!is_dir("$dir/$file") || $file[0] == ".") continue;

				array_push($dlist,$file);
			}
			closedir($handle);
		}
		$num = 0;
		sort($dlist);
		foreach ($dlist as $key => $val)
		{
			$dname = $val;
			if(!$flag)
			{
				if( file_exists("../templates/$val.tpl") )
				{
					$dname = "<a href='?set_theme=$val' title='Click here to use $val for theme'>$val</a>";
				}
			}
			else
			{
				$dname = $val;
				if($_SESSION['UserName'])
				{
					if( file_exists("../templates/$name/$val.tpl") )
					{
						$dname = "<a href='?set_theme=$name/$val' title='Click here to use $val for theme'>$val</a>";
					}
				}
			}
			
			$this->_CC_['content'] .= "<li>$dname<br />".
				"<a onclick=\"ref=window.open('$dir/$val/index.html','designs','left=0,top=0,width=850,height=700,resizable=1,scrollbars=1');ref.focus()\">".
				"<img src='$dir/$val/thumb.jpg' alt='$val' title='Click here to preview $val' /></a></li>";
			$num++;
		}
		$this->_CC_['content'] = "<h2>Designer: $name</h2><br /><h3>Total: $num</h3>".$this->_CC_['content']."</ul></div><br />";
	}
	
        /*-------------\
        | get template |
        \-------------*/
	function getTemplate($file_name)
	{
		if($_SESSION['theme'] && !$this->_CC_['theme'])
		{
			if($_SESSION['theme']=="none")
			{
				$_SESSION['theme'] = "";
			}
			elseif(!$this->_CC_['udfTHEME'])
			{
				$file_name = $_SESSION['theme'];
			}
		}

		list($fname,$ext) = explode(".",$file_name);

		if(!$ext) $ext = "tpl";

		$content = @file_get_contents("./users/".$this->_CC_['member']."/$fname.$ext");
		if(!$content)
		{
			$content = @file_get_contents("../templates/$fname/$ext.tpl");
		}
		if(!$content)
		{
			$content = @file_get_contents("../templates/$fname.$ext");
		}
		if(!$content)
		{
			if($_SESSION['theme']) $_SESSION['theme'] = "";
			$content = @file_get_contents("../templates/default.tpl");
		}
		if(!$content)
		{
			$this->_CC_['FileName'] = "$file_name.$ext";
			$this->opUdfMessage("udf_036"); // error read template
			exit;
		}
		list($this->_CC_header,$this->_CC_body) = explode("^^^^^",$content,2);
	}
	
        /*-------------\
        | use template |
        \-------------*/
	function useTemplate($file_name)
	{
		//$tpl = $this->_CC_[$file_name."_msgs"];
		$tpl = $this->getTplValue("msgs",$file_name);
		if($tpl)
		{
			$this->opUdfMsgs($tpl);
			return;
		}
		
		list($fname,$ext) = explode(".",$file_name);
		if(!$ext) $ext = "tpl";
		$fname .= ".$ext";

		$content = @file_get_contents("../templates/$fname");

		$this->opUdfMsgs($content);
	}
	
	/*---------------\
        | output message |
        ----------------*/
	function opMessage($tpl)
	{
		//$msg = $this->_CC_[$tpl."_msgs"];
		$msg = $this->getTplValue("msgs",$tpl);
		if(!$msg) echo "<h1>(opMessage) Template $tpl not found!</h1>";
		else $this->opUdfMsgs($msg);
	}

	/*---------\
        | get form |
        ----------*/
	function getForm($tpl)
	{
		$msg = $this->getTplValue("frms",$tpl);
		if(!$msg) return "<h3>(getForm) Template $tpl not found!</h3>";
		return $this->subString($msg);
	}

	/*------------\
        | output form |
        -------------*/
	function opForm($tpl)
	{
		$msg = $this->getTplValue("frms",$tpl);
		//echo "opForm($tpl) getTplValue(frms,$tpl)";exit;
		if(!$msg) echo "<h3>(opForm) Template $tpl not found!</h3>";
		else $this->opUdfMsgs($msg);
	}

	/*-----------------\
        | output form data |
        ------------------*/
	function opFormData($tpl)
	{
		echo $this->getTplValue("frms",$tpl);
	}

	/*--------------\
        | get form data |
        ---------------*/
	function getFormData($tpl)
	{
		return $this->getTplValue("frms",$tpl);
	}

	/*-------------------------\
        | get user defined message |
        --------------------------*/
	function getUdfMsg($tpl)
	{
		$msg = $this->getTplValue("strs",$tpl);
		if(!$msg) return "<h1>(getUdfMsg) Template $tpl not found!</h1>";

		return $this->subString($msg);
	}
	
	/*---------------------\
        | get template message |
        ----------------------*/
	function getTplMsg($tpl)
	{
		$msg = $this->getTplValue("msgs",$tpl);
		if(!$msg) return "<h1>(getTplMsg) Template $tpl not found!</h1>";

		return $this->subString($msg);
	}
	
	/*----------------------------\
        | output user defined message |
        -----------------------------*/
	function opUdfMessage($udf)
	{
		$this->_CC_['udf_msg'] = $this->SubString($this->getTplValue("strs",$udf));
		if(!$this->_CC_['udf_msg'])
		{
			echo "<h1>Message $udf not defined!</h1>";
			return;
		}
		$this->opUdfMsgs($this->getTplValue("msgs","user_defined"));
	}
	
        /*---------------------\
        | get template message |
        \---------------------*/
	function getTplValue($table,$tname)
	{
		$q = $this->TEMPLATES->query("SELECT value FROM $table WHERE name = '$tname'");
		list($value) = $q->fetch();

		return stripslashes($value);
	}
			
        /*----------------------\
        | process mail messages |
        \----------------------*/
	function procMailMsgs()
	{
		$uid = $_REQUEST['ID'];
		if( !file_exists("./users/$uid/mail.dbf") )
		{
			$this->MAIL = new SQLiteDatabase("./users/$uid/mail.dbf"); // user mail database
			$this->createDbase("mail","mail");
		}
		else $this->MAIL = new SQLiteDatabase("./users/$uid/mail.dbf"); // mail database


		$this->_CC_['REMOTE'] = $_SERVER['REMOTE_ADDR'];
		$this->_CC_['vfy'] = "";
		/*if($this->username==$_GET['ID'])
		{
			echo "You cannot send mail to yourself";
			return;
		}*/
		//if($this->username!="admin")
		{
			if($_GET['TO']&&$_SESSION['UserName'])
			{
				$this->_CC_['FROM'] = $this->_CC_['fname']." ".$this->_CC_['lname'];
				$this->_CC_['EMAIL'] = $this->_CC_['email'];
			}
		}	
		if(!$_POST['FROM'] || !$_POST['EMAIL'] || !$_POST['SUBJECT'] || !$_POST['MESSAGE'])
		{
			if(!$_GET['TO']) $this->_CC_['vfy'] = 1;
		}
	        else
		{
			if($this->username!=$_SESSION['UserName'])
			{
				if($this->checkVerification()) $this->_CC_['vfy'] = 2;
			}
		}
		if( $this->_CC_['vfy'] == 1 )
		{
			$this->_CC_['wrong_code'] = $this->getUdfMsg("udf_065"); // Missing required info
		}
	        else if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $_POST['EMAIL']))
		{
			if(!$_GET['TO']) $this->_CC_['wrong_code'] = $this->getUdfMsg("udf_086"); // Invalid email;
		}
	        else if($this->_CC_['vfy'] == 2 && !$_SESSION['UserName'])
		{
			$this->_CC_['wrong_code'] = $this->getUdfMsg("udf_066"); // Wrong verification code
		}
	        else
		{
			$this->addMail();
			echo "Your message is successfully sent to ".$_POST['TO'];
			
			$this->username = $this->_CC_['ID'];
			$this->UDB      = new SQLiteDatabase("./users/$this->username/contents.dbf"); // user content database
			$this->getProfile();

			mail($this->_CC_['email'], "You have received a message from ".
			     $_POST['FROM'] , "Subject: ".$_POST['SUBJECT'], "From: ".$this->_CC_['WEBSITE']." Network\n");
					
			return;
		}

		$this->opUdfMsgs($this->getTplValue("msgs","send_mail"));

		return;

	}
	
        /*----------------------\
        | display mail messages |
        \----------------------*/
	function dispMailMsgs($template)
	{
		if(!$_SESSION['UserName'])
		{
			$this->_CC_['content'] =  "You must log in for this operation.";
			return;
		}
		$uname = $_SESSION['UserName'];
		if( !file_exists("./users/$uname/mail.dbf") )
		{
			$this->MAIL = new SQLiteDatabase("./users/$uname/mail.dbf"); // user mail database
			$this->createDbase("mail","mail");
		}
		else $this->MAIL = new SQLiteDatabase("./users/$uname/mail.dbf"); // mail database
		
		if($_REQUEST['delete'])
		{
			$q = $this->MAIL->query("DELETE FROM mail WHERE MailNum='".$_REQUEST['delete']."'");
		}
		$this->_CC_['Member'] = $this->username;
		
		list($header,$body,$footer,$delete) = explode("^^^", $this->getTplValue("msgs",$template));

		$q = $this->MAIL->query("SELECT Count(*) FROM mail'");
		list($this->_CC_['NumItems']) = $q->fetch();

		$this->_CC_['content'] = $this->subString($header)."\n";
		
		$q = $this->MAIL->query("SELECT * FROM mail'");

		while( $q->valid() )
		{
			list($this->_CC_['MailNum'],$this->_CC_['From'],$this->_CC_['Date'],$this->_CC_['eMail'],$this->_CC_['Remote'],
			     $this->_CC_['Subject'],$this->_CC_['Message']) = $q->current();
			$this->_CC_['content'] .= $this->subString($delete); // Delete this message
			$this->_CC_['content'] .= $this->subString($body)."\n";
			$q->next();
		}
		$this->_CC_['content'] .= $this->subString($footer)."\n";
	}
				
        /*---------\
        | add mail |
        \---------*/
	function addMail()
	{
		$uname = $_POST['FROM'];
		$email = $_POST['EMAIL'];
		$subject = sqlite_escape_string($_POST['SUBJECT']);
		$message = sqlite_escape_string($_POST['MESSAGE']);
		$q = $this->MAIL->query("INSERT INTO mail VALUES(NULL,'$uname','".
					$this->_CC_['datetime']."','$email','".$this->_CC_['REMOTE'].
					"','$subject','$message')");
		if ($q === false)
		{
			echo "Error adding mail message";
			exit;
		}
	}
	
        /*----------\
        | get album |
        \----------*/
	function getPhotos($name)
	{
		if(!$this->_CC_['g_max'])  $this->_CC_['g_max'] = 1;
		
		list($album,$pid) = explode(".",$name);
		
		$this->_CC_['g_album']  = $album;
		if(!$this->_CC_['g_album'])
		{
			$album = $this->_CC_['g_album'] = $this->_CC_['album'];
		}
		else $this->_CC_['album'] = $this->_CC_['g_album'];
		
		if($this->_CC_['usite'])
		{
			$this->_CC_['g_folder'] = "./".$this->_CC_['USITE']."/users/$this->username/images/$album/";
		}
		else $this->_CC_['g_folder'] = "./users/$this->username/images/$album/";
		
		$this->_CC_['content'] = "";

		if($this->_CC_['tname'])
		{
			$title = "AND Title LIKE '%".$this->_CC_['tname']."%'";
		}		
		if($this->_CC_['where'])
		{
			$title .= "AND ".$this->_CC_['where'];
		}
		$q = $this->UDB->query("SELECT COUNT(*) FROM Albums WHERE Album='$album' $title");
		list($this->_CC_['g_total']) = $q->fetch();
		
		if($this->_CC_['g_last']) $this->_CC_['g_next'] = $this->_CC_['g_total']-$this->_CC_['g_max'];
		elseif($this->_CC_['g_first']) $this->_CC_['g_next'] = 0;
		elseif($this->_CC_['g_prev']) $this->_CC_['g_next'] -= $this->_CC_['g_max']*2;
		
		if($this->_CC_['g_next'] >= $this->_CC_['g_total']) $this->_CC_['g_next'] = 0;
		elseif($this->_CC_['g_next']<0 || !$this->_CC_['g_next']) $this->_CC_['g_next'] = 0;
		
		if(!$pid) $limit = "LIMIT ".$this->_CC_['g_next'].",".$this->_CC_['g_max'];

		$order = $this->_CC_['order'];
		if(!$order) $order = "aid";
		$q = $this->UDB->query("SELECT * FROM Albums WHERE Album='$album' $title ORDER BY $order $limit");
		if ($q === false)
		{
			echo "SELECT * FROM Albums WHERE Album='$album' $title ORDER BY $order $limit<br>";
			echo "ERROR reading album";
			return;
		}
		$layout = $this->_CC_['layout'];
		if(!$layout) $layout = "gallery_layout";
		$format = $this->getTplValue("msgs",$layout);
		
		$ix  = 0;
		$ext = $this->_CC_['g_next'];
		
		while( $q->valid() )
		{
			list($this->_CC_['g_file'],$this->_CC_['g_num'],$this->_CC_['g_aname'],$this->_CC_['g_name'],$desc,$this->_CC_['g_date']) = $q->current();
			list($this->_CC_['g_desc'],$this->_CC_['g_cmnt']) = explode("^^^",$desc);
			if(!$this->_CC_["g_id_$ext$ix"])
			{
				$this->_CC_["g_id_$ext$ix"]    = $this->_CC_['g_num'];
				$this->_CC_["g_photo_$ext$ix"] = $this->_CC_['g_file'];
				$this->_CC_["g_uname_$ext$ix"] = $this->_CC_['g_name'];
				$this->_CC_["g_desc_$ext$ix"]  = $this->_CC_['g_desc'];
				$this->_CC_["g_cmnt_$ext$ix"]  = $this->_CC_['g_cmnt'];
				$this->_CC_["g_date_$ext$ix"]  = $this->_CC_['g_date'];
			}

			$ix++;
			$this->_CC_['g_curr'] = $this->_CC_['g_next'];
			$this->_CC_['g_next']++;
			if($pid) // photo id provided - show single photo
			{
				if($pid==$this->_CC_['g_num'])
				{
					$this->_CC_['content'] .= $this->SubString($format);
					break;
				}
			}
			else	$this->_CC_['content'] .= $this->SubString($format);

			$q->next();
		}
		if($_SESSION['UserName']==$this->username)
		{
			$this->_CC_['g_delete'] =
				" --- <a href='?Update=gallery&action=delete&album=$album.".
				$this->_CC_['g_file']."' title='Delete this photo'><font color='red'>Delete</font></a>";
			$this->_CC_['g_update'] =
				"<input type='button' value='Edit' onClick=\"window.open('?use=gallery_update&show=$album.".
				$this->_CC_['g_num']."','edit','width=700,height=600,resizable=1,scrollbars=1')\" />";
		}
		$this->_CC_['where'] = $this->_CC_['order'] = "";
	}
	
        /*-------------------------\
        | get image from directory |
        \-------------------------*/
	function getImage($album)
	{
		list($album,$attrs)  = explode(":",$album);
		$attrs = preg_replace("/\"/","'",$attrs);
		$this->_CC_['img_attrs'] = stripslashes($attrs);

		list($album,$id,$first,$last)  = explode(".",$album);
		if($id=="random")
		{
			$id = rand($first,$last);
		}
		elseif($id=="last")
		{
			$q = $this->UDB->query("SELECT aid FROM Albums order by aid desc limit 1");
			list($id) = $q->fetch();
		}
		if($this->_CC_['usite'])
		{
			$this->_CC_['img_album'] = "../".$this->_CC_['usite']."/users/$this->username/images/$album/";
		}
		else $this->_CC_['img_album'] = "./users/$this->username/images/$album/";
				
		$q = $this->UDB->query("SELECT * FROM Albums WHERE Album='$album' AND aid>='$id'");

		list($this->_CC_['img_fname'],$this->_CC_['img_id'],$this->_CC_['img_aname'],
			     $this->_CC_['img_uname'],$this->_CC_['img_desc'],$this->_CC_['img_mdate']) = $q->fetch();

		if(!$this->_CC_['img_fname']) return "<font color='red'>Image $id in $album not found!</font>";

		$this->_CC_['album'] = $album;
		
		$fmt = $this->getTplValue("msgs","show_image"); // get image layout
		if(!$fmt) return "<img src='".$this->_CC_['img_album'].$this->_CC_['img_fname']."' />";
		return $this->subString($fmt);
	}
	
	/*-----------------------\
        | generate html document |
        \-----------------------*/
	function generateHTML()
	{
		$handle = opendir("./");

		while (false !== ($file = readdir($handle)))
		{
			if(preg_match("/^(.*)\.html$/",$file,$regs))
			{
				unlink($file);
			}
		}
		closedir($handle);
		@unlink('html.zip');
		$_GET['Page'] = $this->_CC_['PAGE'] = "";
		$this->Page = "";
		$this->opUdfMsgs( "template: ".$this->_CC_['template'] );
		$this->savePage(); // save index.html

		foreach($this->_CC_['menu_list'] as $page)
		{
			$_GET['Page'] = $this->_CC_['PAGE'] = $page;
			list($this->_CC_['Page']) = explode(".",$page);
			$this->Page = "";
			$this->opUdfMsgs( "template: ".$this->_CC_['template'] );
			$this->savePage(); // save this page as .html
			
			$html_files .= "$page.html,";
		}
		$this->_CC_['Page'] = $_GET['Page'] = $this->_CC_['PAGE'] = "_sitemap_";
		$this->Page = "";
		$this->opUdfMsgs( "template: ".$this->_CC_['template'] );
		$this->savePage(); // save sitemap.html
		//$this->generateHTMLpage( "menu1" );


		include_once('../codes/pclzip.lib.php');
		$archive = new PclZip('html.zip');
		$v_list = $archive->create($html_files . "index.html,_sitemap_.html");
		if ($v_list == 0)
		{
			die("Error : ".$archive->errorInfo(true));
		}
		exit;
	}
	
	/*----------------------------\
        | generate html document page |
        \---------------------------*/
	function generateHTMLpage($parent)
	{
		$this->Page = "";
		$this->opUdfMsgs( "template: ".$this->_CC_['template'] );
		$this->savePage();
		exit;
	}
	
	/*---------------\
        | save this page |
        \---------------*/
	function savePage()
	{
		if($_GET['generate'] != "html") return;
		
		if($_SESSION['UserName'] != "admin")
		{
			echo "<font size='4' color='red'>This operation is only available to admin!</font>";
			return;
		}
		$this->Page = preg_replace("/(\'\?Page\=([a-zA-Z0-9\_\.\ \-]+)\')/","'$2.html'",$this->Page,-1);

		$this->Page = preg_replace("/(([\'|\"])\?)/","$2/index.php?",$this->Page,-1);

		$page = $this->_CC_['PAGE'];
		if($this->_CC_['Main']) $page .= ".".$this->_CC_['Main'];
		if(!$_GET['Page']) $page = "index";

		$fp = fopen("$page.html","w");

		fwrite($fp, $this->Page);
		fclose($fp);
		$this->Page = "";

		echo "<a href='../".$this->_CC_['USITE']."/$page.html'>$page.html</a> is generated.";
	}

	/*-----------------\
        | get blog content |
        \-----------------*/
	function getBlogContent($pname)
	{
		$bid = $this->_CC_['bid'];
		//if(!$bid) $bid = 1;
		$tpage = $this->_CC_['PAGE'];

		if(!$this->_CC_['admin'])
		{
			$this->BLOG = new SQLiteDatabase("./users/".$this->_CC_['member']."/blog.dbf"); // user blog database
		}
		$q = $this->BLOG->query("SELECT COUNT(*) FROM blog WHERE Page='$pname'");
		if ($q === false)
		{
			$this->createDbase("blog","blog");
			$q = $this->BLOG->query("SELECT COUNT(*) FROM blog WHERE Page='$pname'");
		}
		list($cnt) = $q->fetch();
		if(!$cnt)
		{
			$this->BLOG->query("INSERT INTO blog VALUES(NULL, '$pname', '0', '0', ".
					 "'".$_SESSION['UserName']."', '', '', ".
					 "'$pname', 'Please update this content...', '".
					   $this->_CC_['datetime']."')");
			$bid = 1;
		}
		$q = @$this->BLOG->query("SELECT * FROM blog WHERE Page='$pname' AND Reply='0' ORDER BY bid");
		$q->valid();
		while( 1 )
		{
			list($this->_CC_['this_bid'],$this->_CC_['this_page'],$this->_CC_['this_reply'],$this->_CC_['this_cmnts'],
			     $this->_CC_['this_username'],$this->_CC_['this_website'],$this->_CC_['this_email'],
			     $this->_CC_['this_topic'],$this->_CC_['this_content'],$this->_CC_['this_datetime']) = $q->current();
			$q->next();
			if($this->_CC_['this_bid'] == $bid)
			{
				list($this->_CC_['next_bid'],$page,$reply,$cmnts,$username,$website,$email,$this->_CC_['next_topic']) = $q->current();
				break;
			}
			if($q->valid())
			{
				$this->_CC_['prev_topic'] = $this->_CC_['this_topic'];
				$this->_CC_['prev_bid']   = $this->_CC_['this_bid'];
			}
			else
			{
				break;
			}
		}
		$this->_CC_['bid'] = $this->_CC_['this_bid'];
		if($this->_CC_['prev_bid'])
		{
			$this->_CC_['prev_bid'] = "&laquo; <a href='?Page=$tpage&bid=".$this->_CC_['prev_bid']."'>".$this->_CC_['prev_topic']."</a>";
		}
		if($this->_CC_['next_bid'])
		{
			$this->_CC_['next_bid'] = "<a href='?Page=$tpage&bid=".$this->_CC_['next_bid']."'>".$this->_CC_['next_topic']."</a> &raquo;";
		}
	}
	
	/*-----------------\
        | get blog content |
        \-----------------*/
	function getBlogComments($pname)
	{
		$this->_CC_['comments'] = "";
		$q = @$this->BLOG->query("SELECT * FROM blog WHERE Page='$pname' AND Reply='".$this->_CC_['this_bid']."'");
		if($q === FALSE)
		{
			$this->_CC_['comments'] = "No Comments";
			return;
		}
		$fmt = $this->getTplValue("msgs","blog_layout");
		$num = 0;
		while( $q->valid() )
		{
			list($this->_CC_['this_bid'],$this->_CC_['this_page'],$this->_CC_['this_reply'],$this->_CC_['this_cmnts'],
			     $this->_CC_['From'],$website,$this->_CC_['this_email'],
			     $this->_CC_['this_topic'],$this->_CC_['Comment'],$this->_CC_['Date']) = $q->current();
			if($website) $this->_CC_['Website'] = "<a href='http://$website'>$website</a>";
			else $this->_CC_['Website'] = "";
			$q->next();
			if($this->_CC_['member']==$_SESSION['UserName'] && $this->cwd == $_SESSION['CWD'])
			{
				$this->_CC_['comment_number'] = $num;
				$this->_CC_['comments'] .= $this->getUdfMsg("udf_060"); // Delete this comment
			}
			$this->_CC_['comments'] .= $this->subString($fmt)."\n";
			$num++;
		}
		if($this->_CC_['vfy'] == 1) $this->_CC_['wrong_code'] = $this->getUdfMsg("udf_065"); // Missing required info
		else if($this->_CC_['vfy'] == 2 && !$_SESSION['UserName']) $this->_CC_['wrong_code'] = $this->getUdfMsg("udf_066"); // Wrong verification code

		if($_SESSION['UserName'] && !$this->_CC_['FROM']) $this->_CC_['FROM'] = $_SESSION['FirstName'];
		$this->_CC_['COMMENT']   = stripslashes(trim($this->_CC_['COMMENT']));
		$this->_CC_['comments'] .= $this->getForm("blog_comment")."\n";
	}
			
        /*--------------------\
        | get members listing |
        \--------------------*/
	function getMembers($template)
	{
		if($this->_CC_['USITE']=="_members") $this->_CC_['homepage'] = "Profile";
		else $this->_CC_['homepage'] = "Home";
		
		$this->_CC_['content'] = "";

		if($this->cwd == "_main" || $this->cwd == "_forum") $template = "members_listing";
		if(!$template)
		{
			$template = "members_list";
		}
		list($header,$fmt,$footer,$order) = explode("^^^",$this->getTplValue("msgs",$template));
		
		if(!$this->_CC_['max'])  $this->_CC_['max'] = 5;
		elseif($this->_CC_['max']>20)  $this->_CC_['max'] = 20;

		if($this->_CC_['Name'])
		{
			if($where) $where .= " AND ";
			else $where .= "WHERE ";
			$this->_CC_['Name'] = trim($this->_CC_['Name']);
			$where .= "Name LIKE '%".$this->_CC_['Name']."%'";
		}
		if($this->_CC_['City'])
		{
			if($where) $where .= " AND ";
			else $where .= "WHERE ";
			$this->_CC_['City'] = trim($this->_CC_['City']);
			$where .= "City LIKE '%".$this->_CC_['City']."%'";
		}
		if($this->_CC_['State'])
		{
			if($where) $where .= " AND ";
			else $where .= "WHERE ";
			$this->_CC_['State'] = trim($this->_CC_['State']);
			$where .= "State LIKE '%".$this->_CC_['State']."%'";
		}
		$q = @$this->MEMBERS->query("SELECT COUNT(*) FROM members $where");
		if($q===FALSE)
		{
			if($flag) $this->_CC_['content'] = "<font size='5' color='red'>ERROR READING DATABASE FILE...";
			return;
		}
		list($this->_CC_['NumItems']) = $q->fetch();
	
		if(!$this->_CC_['pnum']) $this->_CC_['pnum'] = 0;
		$rnum = $this->_CC_['pnum']*$this->_CC_['max'];
		if($rnum>=$this->_CC_['NumItems']) $rnum = $this->_CC_['NumItems']-$this->_CC_['max'];
		
		if($this->_CC_['last']) $this->_CC_['next'] = $this->_CC_['NumItems']-$this->_CC_['max'];
		elseif($this->_CC_['first']) $this->_CC_['next'] = 0;
		elseif($this->_CC_['prev']) $this->_CC_['next'] -= $this->_CC_['max']*2;
		
		if($this->_CC_['next'] >= $this->_CC_['NumItems']) $this->_CC_['next'] = 0;
		elseif($this->_CC_['next']<0 || !$this->_CC_['next']) $this->_CC_['next'] = 0;


		if(!$order) $order = "ORDER BY ID";
		$limit = "LIMIT ".$this->_CC_['next'].",".$this->_CC_['max'];
		$q = $this->MEMBERS->query("SELECT * FROM members $where $order $limit");

		$delete = 0;
		//if($_SESSION['UserName']=="admin" && $this->cwd=="_main" && $this->cwd == $_SESSION['CWD']) $delete++;
		if($_SESSION['UserName']=="admin" && $this->cwd == $_SESSION['CWD']) $delete++;

		while( $q->valid() )
		{
			list($this->_CC_['ID'],$this->_CC_['email'],$this->_CC_['name'],
			     $this->_CC_['zip'],$this->_CC_['district'],$this->_CC_['city'],$this->_CC_['state'],
			     $this->_CC_['company'],$this->_CC_['profile'],$this->_CC_['logins'],
			     $this->_CC_['points'],$this->_CC_['spent'],
			     $this->_CC_['credits'],$this->_CC_['cused'],$this->_CC_['cpaid'],$this->_CC_['cLimit'],
			     $this->_CC_['cdate'],$this->_CC_['mdate'],$this->_CC_['website'],
			     $this->_CC_['nblogs'],$this->_CC_['ntopics'],$this->_CC_['nposts']) = $q->current();
			$q->next();
			$rnum++ ;
			
			if($this->_CC_['website']) $this->_CC_['website'] = "<a href='http://".$this->_CC_['website'].
				"/?usite=".$this->_CC_['ID']."' title='Visit ".$this->_CC_['company']." website'>Website</a>";
			
			if($delete) $this->_CC_['delete'] = "<a href='?delete_member=".$this->_CC_['ID']."'><font color='red'>delete</font></a>";

			$content .= $this->subString($fmt)."\n";
		}
		$this->_CC_['next'] += $this->_CC_['max'];

		//$header = $style.$this->subString($header);
		//$this->_CC_['content'] .= $this->subString($footer);
		$this->_CC_['content'] = $this->subString($header).$content.$this->subString($footer);
	}
		
        /*--------------------------\
        | update member login count |
        \--------------------------*/
	function updateMemberLogin()
	{
		$q = $this->MEMBERS->query("SELECT Logins FROM members WHERE ID='$this->username'");
		if($q) list($count) = $q->fetch();
		$count++;
		$this->MEMBERS->query("UPDATE members SET Logins='$count', mdate='".$this->_CC_['datetime']."' WHERE ID='$this->username'");
	}
		
        /*---------------------------\
        | update member website link |
        \---------------------------*/
	function updateWebsite($uname,$sname)
	{
		$this->MEMBERS = new SQLiteDatabase("./members.dbf"); // members database
		$q = $this->MEMBERS->query("UPDATE members SET Website='$sname' WHERE ID='$uname'");
		if(!$q) echo "Error encountered... updateWebsite($uname,$sname)";

		$q = $this->MEMBERS->query("SELECT Points,Credits FROM points WHERE Action='Upgrade'");
		list($upoints,$ucredits) = $q->fetch();
		
		$this->UDB  = new SQLiteDatabase("./users/$uname/contents.dbf"); // Transactions database
		$this->UDB->query("INSERT INTO transactions VALUES('".$this->_CC_['datetime'].
					   "','Upgrade','Upgrade Account','$uname','$upoints','$ucredits')");		
	
		$q = $this->MEMBERS->query("SELECT Name,Points,pSpent,Credits,cUsed,cPaid,cLimit FROM members WHERE ID='$uname'");
		list($name,$points,$spent,$credits,$cused,$paid,$limit) = $q->fetch();

		$points -= $spent;
		if($points<$upoints)
		{
			$upoints = $points;
		}
		$ucredits -= $upoints;
		$spent  += $upoints;
		$cused  += $ucredits;
		$q = $this->MEMBERS->query("UPDATE members SET pSpent='$spent',cUsed='$cused' WHERE ID='$uname'");
		
		$this->MEMBERS->query("INSERT INTO activities VALUES(NULL,'upgrade','$uname','$name','upgraded account','?Page=Profile&member=$uname','".
				      $this->_CC_['datetime']."')");
	}
	
        /*-------------\
        | last user id |
        \-------------*/
	function lastID()
	{
		$q = $this->MEMBERS->query("SELECT ID FROM members ORDER BY ID DESC LIMIT 1");
		list($id) = $q->fetch();
		return $id;
	}
	
	/*-----------------------\
        | get members activities |
        \-----------------------*/
	function getActivities($member)
	{
		$template = "recent_activities";
		if($member=="member")
		{
			$where = "WHERE UID='".$this->_CC_['member']."'";
			$template = "member_activities";
		}
		$q = @$this->MEMBERS->query("SELECT * FROM activities $where ORDER BY mdate DESC LIMIT 10");
		if($q === FALSE)
		{
			$this->_CC_['content'] = "No Activities";
			return;
		}
		list($header,$body,$footer) = explode("^^^", $this->getTplValue("msgs",$template));
		$content = "";
		while( $q->valid() )
		{
			list($this->_CC_['this_aid'],$this->_CC_['this_icon'],$this->_CC_['this_uid'],$this->_CC_['this_uname'],
			     $this->_CC_['this_desc'],$this->_CC_['this_url'],$this->_CC_['this_date']) = $q->current();
			$q->next();
			$content .= $this->subString($body)."\n";
		}
		$this->_CC_['content'] = $header.$content.$footer;
	}
	
        /*-----------------------------\
        | get total number of lintings |
        \-----------------------------*/
	function totalListings()
	{
		$this->LISTINGS = new SQLiteDatabase("./listings.dbf"); // listing database

		$q = @$this->LISTINGS->query("SELECT COUNT(*) FROM listings");
		if ($q === false)
		{
			return 0;
		}
		list($total) = $q->fetch();
		echo $total;
		exit;
	}
	
        /*--------------------\
        | make user directory |
        \--------------------*/
	function makeDirectory($dir)
	{
		$this->_CC_['DirName'] = $dir;
		if (is_dir($dir))
		{
			$this->opUdfMessage("udf_006"); //<h3>User <code>{DirName}</code> exists!<br /><br />Operation aborted.</h3>

			exit;
		}
		if(!mkdir($dir, 0755))
		{
			$this->opUdfMessage("udf_007"); //<h3>Unable to make directory <code>{DirName}</code></h3>
			exit;
		}
		$this->_CC_['status'] .= $this->getUdfMsg("udf_008"); //<br />Directory <code>{DirName}</code> is sucessfully created.<br />
		return 0;
	}
	
        /*----------------------\
        | create database table |
        \----------------------*/
	function createDbase($dbase,$table)
	{
		$date    = $this->_CC_['datetime'];
		$website = $this->_CC_['WEBSITE'];
		$domain  = $this->_CC_['DOMAIN'];
		switch($dbase)
		{
			case 'profile':
				$this->UDB->query("CREATE TABLE _profile_".
					"( uName CHAR(255) PRIMARY KEY, Zip CHAR(20), District CHAR(2), State CHAR(2), ".
					"City CHAR(255), fName CHAR(255), lName CHAR(255), About TEXT, ".
					"Password CHAR(255), eMail CHAR(255), cName CHAR(255), cTitle CHAR(255), Slogan CHAR(255),".
					"copyRight CHAR(255), Editor CHAR(20), eMode CHAR(20), Template CHAR(50),".
					"cDate INTEGER, mDate INTEGER)");	
				break;
			case 'transaction':
				$this->UDB->query("CREATE TABLE transactions".
					" (tDate CHAR(255) PRIMARY KEY, Activity CHAR(255), Description CHAR(255), ".
					"Member CHAR(255), Points INTEGER, Credits INTEGER)");
				break;
			case 'document':
				$this->UDB->query("CREATE TABLE $table".
					" ( Name CHAR(255) PRIMARY KEY, cid INTEGER, Type CHAR(20), ".
					"Header CHAR(255), Content TEXT, mdate INTEGER)");
				break;
			case 'menu':
				$this->UDB->query("CREATE TABLE $table".
					" ( Name CHAR(255) PRIMARY KEY, mid INTEGER, Main CHAR(255), Type CHAR(20), ".
					"Hide CHAR(1), Theme CHAR(20), Title CHAR(255), Attrs CHAR(255), Meta TEXT, ".
					"Desc TEXT, mdate INTEGER)");
				break;
			case 'album':
				$this->UDB->query("CREATE TABLE $table".
					   " ( Name CHAR(255) PRIMARY KEY, aid INTEGER, Album CHAR(20), ".
					   "Title CHAR(255), Description TEXT, mdate INTEGER)");
				break;
			case 'member':
				$this->MEMBERS->query("CREATE TABLE members".
					" (ID CHAR(255) PRIMARY KEY, eMail CHAR(80), Name CHAR(255), ".
					"Zip CHAR(20), District CHAR(2),City CHAR(255), State CHAR(2), ".
					"Organization CHAR(255), Profile TEXT, Logins INTEGER, Points INTEGER, pSpent INTEGER, ".
					"Credits INTEGER, cUsed INTEGER, cPaid INTEGER, cLimit INTEGER, ".
					"cdate INTEGER, mdate INTEGER, Website CHAR(255), nBlogs INTEGER, nTopics INTEGER, nPosts INTEGER)");
				$this->MEMBERS->query("CREATE TABLE points".
					" (Action CHAR(255) PRIMARY KEY, UID CHAR(255), Description CHAR(255), ".
					"Points INTEGER, Credits INTERGER)");
				$this->MEMBERS->query("INSERT INTO points VALUES('Signup','admin','Signup Bonus','5','')");
				$this->MEMBERS->query("CREATE TABLE activities".
					" (aid INTEGER PRIMARY KEY, Icon CHAR(255), UID CHAR(255), uName CHAR(255), ".
					"Description CHAR(255), URL CHAR(255), mdate INTEGER)");
				break;
			case 'blog':
				$this->BLOG->query("CREATE TABLE $table".
					" ( bid INTEGER PRIMARY KEY, Page CHAR(80), Reply INTEGER, nCmmnts INTEGER, ".
					"User CHAR(80), Website CHAR(80), eMail CHAR(80), ".
					"Topic CHAR(80), Content TEXT, mdate INTEGER)");
				break;
			case 'forum':
				$this->FORUM->query("CREATE TABLE $table".
					" ( fid INTEGER PRIMARY KEY, Thread CHAR(80), Reply INTEGER, nPosts INTEGER, ".
					"UID INTEGER, User CHAR(80), Website CHAR(80), eMail CHAR(80), Topic CHAR(255), ".
					"Content TEXT, mdate INTEGER)");
				break;
			case 'stat':
				$this->FORUM->query("CREATE TABLE statistics".
					" ( Forum CHAR(80) PRIMARY KEY, Topic CHAR(255), Description TEXT, ".
					"Started CHAR(80), Last CHAR(80), ".
					"nTopics INTEGER, nPosts INTEGER, sDate INTEGER, lDate INTEGER)");
				break;
			case 'invite':
				$this->INVITES->query("CREATE TABLE $table".
					" (Invite INTEGER PRIMARY KEY, FromName CHAR(255), ToName CHAR(255), ".
					"cdate INTEGER, sdate INTEGER, pdate INTEGER)");
				break;
			case 'site':
				$this->SITES->query("CREATE TABLE $table".
					" (Name CHAR(255) PRIMARY KEY, Site CHAR(255), Description CHAR(255))");
				break;
			case 'mail':
				$this->MAIL->query("CREATE TABLE $table".
					" (MailNum INTEGER PRIMARY KEY, uName CHAR(255), mDate INTEGER, eMail CHAR(255), ".
					"Remote CHAR(255), Subject CHAR(255), Message TEXT)");
				break;
			case 'design':
				$this->DESIGNS->query("CREATE TABLE $table".
				      " ( id INTEGER PRIMARY KEY, Design CHAR(80), Author CHAR(80), DID INTEGER, ".
				      "Desc TEXT, Theme CHAR(80), Downloads INTEGER, mdate INTEGER)");
				break;
		}

		return;
	}

}
?>